package com.sdkx.app.fragment;

import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.sdkx.app.R;
import com.sdkx.app.ViewModel.AirDataViewModel;
import com.sdkx.app.ViewModel.AirWayManager;
import com.sdkx.app.ViewModel.CurAirWay;
import com.sdkx.app.ViewModel.WayPointManager;
import com.sdkx.app.adapter.RoutePointAdapter;
import com.sdkx.app.fragment.waypoints.TabWpFragment;
import com.sdkx.app.model.AirWay;
import com.sdkx.app.model.WayPoint;
import com.sdkx.app.view.ClearEditText;

import java.util.ArrayList;
import java.util.List;

import static android.support.design.widget.TabLayout.*;

public class RouteEditFragment extends BaseFragment implements View.OnClickListener {
    private List<WayPoint> editAirway;  //当前选择航线
    private ListView editlist;//wplist,
    //    private SideBar sidebar;
    public final static String MODE_CURRENT = "current";
    public final static String MODE_EDIT = "edit";
    public final static String MODE_ADD = "add";
    private String AWname;
    private RoutePointAdapter editrouteadapter;
    ArrayList<Fragment> fragments = new ArrayList<>();
    private TabLayout tabLayout;
    private ViewPager viewPager;
    TextView airwayName;
    String mode;
    String editAirWayName;
    private Observer<WayPoint> awPointObserver;
    private ArrayList<String> mTitleList = new ArrayList<String>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_menu_routeedit, null);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tabLayout = view.findViewById(R.id.tablayout);
        viewPager = view.findViewById(R.id.viewpager);

//        tabLayout.addTab(tabLayout.newTab().setText(R.string.nearest));
//        tabLayout.addTab(tabLayout.newTab().setText("航点"));
//        tabLayout.addTab(tabLayout.newTab().setText("机场"));
//        tabLayout.addTab(tabLayout.newTab().setText("自定义"));
        view.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        View nearview = getLayoutInflater().inflate(R.layout.wp_tab_item, null);
        TextView txtnearview = nearview.findViewById(R.id.titlename);
        txtnearview.setText("附近");
        Tab neartab = tabLayout.newTab();
        neartab.setCustomView(nearview);
        tabLayout.addTab(neartab);


        View wpview = getLayoutInflater().inflate(R.layout.wp_tab_item, null);
        TextView txtwpview = wpview.findViewById(R.id.titlename);
        txtwpview.setText("航点");
        Tab wptab = tabLayout.newTab();
        wptab.setCustomView(wpview);
        tabLayout.addTab(wptab);


        View airview = getLayoutInflater().inflate(R.layout.wp_tab_item, null);
        TextView txtairview = airview.findViewById(R.id.titlename);
        txtairview.setText("机场");
        Tab airtab = tabLayout.newTab();
        airtab.setCustomView(txtairview);
        tabLayout.addTab(airtab);


        Tab persiontab = tabLayout.newTab();
        View tabview = getLayoutInflater().inflate(R.layout.wp_tab_item, null);
        TextView txtpview = tabview.findViewById(R.id.titlename);
        txtpview.setTextSize(20);
        persiontab.setCustomView(tabview);
        tabLayout.addTab(persiontab);

        fragments.add(new NearFragment());
        fragments.add(new WpFragment());
        fragments.add(new AirFragment());
        fragments.add(new PersionFragment());
        viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return mTitleList.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public android.support.v4.app.Fragment getItem(int position) {
                return fragments.get(position);
            }
        });

        tabLayout.addOnTabSelectedListener(new OnTabSelectedListener() {
            @Override
            public void onTabSelected(Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(Tab tab) {

            }

            @Override
            public void onTabReselected(Tab tab) {

            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.getTabAt(position).select();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
//                tabLayout.setSelected();
            }
        });
        mTitleList.add(getActivity().getString(R.string.nearest));
        mTitleList.add("航点");
        mTitleList.add("机场");
        mTitleList.add("自定义");
        view.findViewById(R.id.tv_all_air_spaces2).setOnClickListener(this);
        view.findViewById(R.id.save).setOnClickListener(this);
        airwayName = view.findViewById(R.id.editText2);
        editlist = (ListView) view.findViewById(R.id.routeitems);
        editrouteadapter = new RoutePointAdapter(getActivity());
        Bundle bundle = getArguments();
        if (bundle != null) {
            mode = bundle.getString("mode");
            switch (mode) {
                case MODE_CURRENT: {
                    airwayName.setText(CurAirWay.getInstance().getName());
                    editrouteadapter.setWayPoints(CurAirWay.getInstance().getList());
                }
                break;
                case MODE_EDIT: {
                    editAirWayName = bundle.getString("AIRWAY_NAME");
                    List<WayPoint> points = AirWayManager.getWayPointsInAirWay(editAirWayName);
                    if (points != null && points.size() > 0) {
                        editrouteadapter.setWayPoints(points);
                        airwayName.setText(editAirWayName);
                    }
                }
                break;
                case MODE_ADD:
                    break;
            }

        } else {
            mode = "add";
        }

        MutableLiveData<WayPoint> liveDataAdd = ViewModelProviders.of(getActivity()).get(AirDataViewModel.class).getWayPointLiveData();
        awPointObserver = new Observer<WayPoint>() {
            @Override
            public void onChanged(@Nullable WayPoint point) {
                if (point == null) return;
                List<WayPoint> points = editrouteadapter.getWayPoints();
                for (WayPoint po : points) {
                    if (po.getId() == point.getId()) {
                        return;
                    }
                }
                points.add(point);
                editrouteadapter.setWayPoints(points);
            }
        };
        liveDataAdd.observe(getActivity(), awPointObserver);

        editlist.setAdapter(editrouteadapter);
        editlist.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    editrouteadapter.clearSelect();
                }
                return false;
            }
        });

        view.findViewById(R.id.swap_down).setOnClickListener(this);
        view.findViewById(R.id.swap_up).setOnClickListener(this);
        view.findViewById(R.id.reverse).setOnClickListener(this);
        view.findViewById(R.id.save).setOnClickListener(this);
        view.findViewById(R.id.clearall).setOnClickListener(this);
        view.findViewById(R.id.deleteitem).setOnClickListener(this);
        //        sidebar = (SideBar) view.findViewById(R.id.sidebar);
        // 设置右侧触摸监听
//
//        sidebar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
//
//            @Override
//            public void onTouchingLetterChanged(String s) {
//                // 该字母首次出现的位置
//                int position = wpListAdapter.getPositionForSection(s
//                        .charAt(0));
//                if (position != -1) {
//                  //  wplist.setSelection(position);
//                }
//
//            }
//        });
        //搜索


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_all_air_spaces2:
                goBack();
                break;
            case R.id.swap_down:
                editrouteadapter.swapDown();
                break;
            case R.id.swap_up:
                editrouteadapter.swapUp();
                break;
            case R.id.reverse:
                editrouteadapter.reverse();
                break;
            case R.id.clearall:
                editrouteadapter.clearAll();
                break;
            case R.id.deleteitem:
                editrouteadapter.delete();
                break;
            case R.id.save: {
                String awName = airwayName.getText().toString();
                if (TextUtils.isEmpty(awName)) {
                    Toast.makeText(getContext(), "请输入航线名称", Toast.LENGTH_SHORT).show();
                    return;
                }
                List<WayPoint> wayPoints = editrouteadapter.getWayPoints();
                if (wayPoints.size() == 0) {
                    Toast.makeText(getContext(), "请添加航点", Toast.LENGTH_SHORT).show();
                    return;
                }
                switch (mode) {
                    case MODE_ADD:
                        if (!AirWayManager.cotains(awName)) {
                            AirWay airWay = new AirWay();
                            airWay.setName(awName);
                            airWay.setType(AirWay.TYPE_CUSTOM);
                            airWay.setIsEdit(true);
                            airWay.setIsShow(true);
                            if (!AirWayManager.insert(airWay)) {
                                Toast.makeText(getContext(), "存储航线失败", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            AirWayManager.updateWayPointsInAirWay(awName, wayPoints);
                            Toast.makeText(getContext(), awName + "航线保存成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getContext(), "名称重复", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case MODE_CURRENT: {
                        if (!AirWayManager.cotains(awName)) {
                            AirWay airWay = new AirWay();
                            airWay.setName(awName);
                            airWay.setType(AirWay.TYPE_CUSTOM);
                            airWay.setIsEdit(true);
                            airWay.setIsShow(true);
                            if (!AirWayManager.insert(airWay)) {
                                Toast.makeText(getContext(), "存储航线失败", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        } else {
                            AirWay airWay = AirWayManager.getItem(awName);
                            airWay.setName(awName);
                            airWay.update(airWay.getId());
                        }
                        AirWayManager.updateWayPointsInAirWay(awName, wayPoints);
                        CurAirWay.getInstance().setName(awName);
                        CurAirWay.getInstance().setList(wayPoints);
                        Toast.makeText(getContext(), "当前航线保存成功", Toast.LENGTH_SHORT).show();
                    }
                    break;
                    case MODE_EDIT:
                        AirWay airWay = AirWayManager.getItem(editAirWayName);
                        airWay.setName(awName);
                        airWay.update(airWay.getId());
                        AirWayManager.updateWayPointsInAirWay(awName, wayPoints);
                        Toast.makeText(getContext(), awName + "航线保存成功", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
            break;
        }
    }

    private EditText getEditText2() {
        return (EditText) getView().findViewById(R.id.editText2);
    }


    public void setEditAirway(List<WayPoint> Airwaywps, String AirWayName) {
        editAirway = Airwaywps;
        AWname = AirWayName;
    }

    @Override
    public void onDestroyView() {
        MutableLiveData<WayPoint> liveDataAdd = ViewModelProviders.of(getActivity()).get(AirDataViewModel.class).getWayPointLiveData();
        liveDataAdd.removeObserver(awPointObserver);
        liveDataAdd.setValue(null);
        super.onDestroyView();
    }

    public static class NearFragment extends BaseWpFragment {
        @Override
        public List<WayPoint> getmWPList() {
            return super.getmWPList();
        }
    }

    public static class AirFragment extends BaseWpFragment {
        int[] types = {WayPoint.WayPointType.MILITARY_AIRPORT.ordinal(),
                WayPoint.WayPointType.AIS_AIRPORT.ordinal(),
                WayPoint.WayPointType.AM_AIRPORT.ordinal(),
                WayPoint.WayPointType.PERSON_AIRPORT.ordinal()
        };

        @Override
        public List<WayPoint> getmWPList() {
            return WayPointManager.getItemsByTypelimit(types, 0, 30);
        }

        @Override
        protected List<WayPoint> getPageList(int curcout, int pagesize) {
            return WayPointManager.getItemsByTypelimit(types, curcout, 30);
        }

        @Override
        protected List<WayPoint> getSearchData(String keywords) {
            return WayPointManager.serchWayPoint(types, keywords);
        }
    }

    public static class WpFragment extends BaseWpFragment {
        int[] types = {
                WayPoint.WayPointType.AIS_NDB.ordinal(),
                WayPoint.WayPointType.AIS_VOR_DME.ordinal(),
                WayPoint.WayPointType.AIS_POINT.ordinal(),
                WayPoint.WayPointType.MILITARY_POINT.ordinal()
        };

        @Override
        public List<WayPoint> getmWPList() {
            return WayPointManager.getItemsByTypelimit(types, 0, 30);
        }

        @Override
        protected List<WayPoint> getPageList(int curcout, int pagesize) {
            return WayPointManager.getItemsByTypelimit(types, curcout, 30);
        }

        @Override
        protected List<WayPoint> getSearchData(String keywords) {
            return WayPointManager.serchWayPoint(types, keywords);
        }
    }

    public static class PersionFragment extends BaseWpFragment {
        int[] types = {
                WayPoint.WayPointType.PERSON_POINT.ordinal()
        };

        @Override
        public List<WayPoint> getmWPList() {
            //TODO：数据库接口更改，需要重新编写代码逻辑
            return WayPointManager.getItemsByTypelimit(types, 0, 30);
        }

        @Override
        protected List<WayPoint> getPageList(int curcout, int pagesize) {
            //TODO：数据库接口更改，需要重新编写代码逻辑
            return WayPointManager.getItemsByTypelimit(types, curcout, 30);
        }

        @Override
        protected List<WayPoint> getSearchData(String keywords) {
            return WayPointManager.serchWayPoint(types, keywords);
        }
    }

    public static class BaseWpFragment extends TabWpFragment {
        @Override
        protected void onListItemClicked(View view, WayPoint point, int pos) {
            MutableLiveData<WayPoint> liveData = ViewModelProviders.of(getActivity()).get(AirDataViewModel.class).getWayPointLiveData();
            liveData.setValue(point);
        }
    }
}
